package com.apes.framework.plugin.form.parser.element;

import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.filereader.xml.ApesElement;
import com.apes.framework.plugin.form.parser.matcher.AttrsMatcher;
import com.apes.framework.plugin.form.parser.matcher.ExpressionMatcher;
import com.apes.framework.plugin.form.parser.node.FormNodeParser;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 功能：button解析
 *
 * @author xul
 * @create 2018-04-16 16:12
 */
@Component
public class ButtonElementParser extends AbstractElementParser {

    /**
     * 可解析的元素列表
     **/
    private final String[] elementNames = {"button"};

    /**
     * 功能：可解析节点域
     */
    @Override
    public String getDomain() {
        return FormNodeParser.domain;
    }

    /**
     * 功能：可解析的元素列表
     */
    @Override
    public String[] getNames() {
        return elementNames;
    }

    @Override
    public Map parse(ApesElement element) {
        Map node = super.parse(element);
        /** 处理 callback 元素**/
        element.getNestedElements().stream().filter(e -> e.getName().equals("callback"))
                .forEach(e -> node.put("callback", e.parse()));
        return node;
    }

    @Override
    protected void parseAttributes(Map node, Map<String, String> attributes) {
        if (!attributes.containsKey("step")) {
            attributes.put("step", "one");
        }
        if (!attributes.containsKey("style")) {
            attributes.put("style", "default");
        }
        if (!attributes.containsKey("wf")) {
            attributes.put("wf", "false");
        }
        if (!attributes.containsKey("confirm")) {
            attributes.put("confirm", "false");
        }
        attributes.forEach((k, v) -> {
            if (k.equals("string")) {
                node.put("label", v);
            } else if (k.equals("type")) {
                node.put("operation", v);
            } else if (k.equals("name")) {
                node.put("id", v);
            } else if (k.equals("attrs")) {
                Map<String, String> attrs = new AttrsMatcher().parse(v.trim());
                attrs.forEach((k1, v1) -> {
                    node.put(k1, v1.replace(ExpressionMatcher.getPlaceholder(), "ctx."));
                });
            } else {
                node.put(k, v);
            }
        });
    }

}
